package com.example.springboot;

import com.example.springboot.util.IndexUtil;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Created by tangmayao on 2018/4/4.
 */
public class TestLuceneCrud {


    @org.junit.Test
    public void initIndex() {
        IndexUtil indexUtil = new IndexUtil();
        indexUtil.index();

    }

    private Analyzer analyzer;
    private IndexWriterConfig indexWriterConfig;
    private Directory directory;
    private IndexWriter indexWriter;
    private IndexReader indexReader;


    @Before
    public void before() {


        try {
            analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
            directory = FSDirectory.open(new File("E:\\java-source\\lucene\\lucene-index\\2"));
            indexWriterConfig = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);

            indexWriter = new IndexWriter(directory, indexWriterConfig);
            indexReader = DirectoryReader.open(directory);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Test
    public void query() {
        try {

            //通过reader可以有效的获取到文档的数量
            System.out.println("numDocs:" + indexReader.numDocs());
            System.out.println("maxDocs:" + indexReader.maxDoc());
            System.out.println("deleteDocs:" + indexReader.numDeletedDocs());
            indexReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Test
    public void addIndex() {
        Document doc = new Document();
        doc.add(new StringField("id", "20", Field.Store.YES));
        doc.add(new StringField("email", "tangmayao@qq.com", Field.Store.YES));
        doc.add(new TextField("content", "hello hello", Field.Store.NO));
        doc.add(new StringField("name", "tangmayao", Field.Store.YES));
        //存储数字
        doc.add(new IntField("attach", 1, Field.Store.YES));
        //存储日期
        doc.add(new LongField("date", new Date().getTime(), Field.Store.YES));

        try {
            indexWriter.addDocument(doc);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                indexWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void queryParser() {
        try {
            QueryParser queryParser = new QueryParser(Version.LUCENE_CURRENT, "content", analyzer);
            Query query = queryParser.parse("hello");

            IndexSearcher searcher = getSearcher();
            TopDocs tds = searcher.search(query, 10);

            ScoreDoc[] sdc = tds.scoreDocs;
            for (ScoreDoc doc : sdc) {
                Document document = searcher.doc(doc.doc);
                System.out.println("name:" + document.get("name") + ",," + document.get("content") + ",," + document.get("date"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Test
    public void delete() {

        Term term = new Term("id", "20");
        try {
            indexWriter.deleteDocuments(term);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                indexWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void updateDocument() {
        Term term = new Term("id", "20");

        Document doc = new Document();
        doc.add(new StringField("id", "20", Field.Store.YES));
        doc.add(new StringField("email", "tangmayao@qq.com", Field.Store.YES));
        doc.add(new TextField("content", "hello hello hello hello", Field.Store.NO));
        doc.add(new StringField("name", "tangmayao123123", Field.Store.YES));
        //存储数字
        doc.add(new IntField("attach", 1, Field.Store.YES));
        //存储日期
        doc.add(new LongField("date", new Date().getTime(), Field.Store.YES));

        try {
            indexWriter.updateDocument(term, doc);
            indexWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 实现近实时查询，不关闭reader，但是Index有变化时，重新获取reader
     **/
    public IndexSearcher getSearcher() {
        try {
            if (indexReader == null) {
                indexReader = DirectoryReader.open(directory);
            } else {
                DirectoryReader tr = DirectoryReader.openIfChanged((DirectoryReader) indexReader);
                if (tr != null) {
                    indexReader.close();
                    indexReader = tr;
                }
            }
            return new IndexSearcher(indexReader);
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
}